package com.xiang.reggie.web.filter;


import com.alibaba.fastjson.JSON;
import com.xiang.reggie.common.Result;
import com.xiang.reggie.common.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 半山居雾
 * @date 2022/12/14 16:51
 */
@Slf4j
@WebFilter("/*")
public class LoginFilter implements Filter {

    //不登录直接访问操作页面也能进入界面，设置过滤器拦截其他非法操作

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}", request.getRequestURI());

        //1.放行应该直接放行的资源
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",    //移动端发送短信
                "/user/login",       //移动端登录
                "/user/logout",
                //直接放行swagger相关的请求
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        boolean check = check(urls, requestURI);

        if (check) {
            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request, response);
            return;
        }


        //2.1.判断用户是否登录（session）
        if (request.getSession().getAttribute("employee") != null) {
            log.info("用户已登录，用户id：{}",request.getSession().getAttribute("employee"));

            //将id存入ThreadLocal
            Long employeeId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(employeeId);

            filterChain.doFilter(request, response);
            return;
        }

        //2.2.判断用户是否登录（session）
        if (request.getSession().getAttribute("user") != null) {
            log.info("用户已登录，用户id：{}",request.getSession().getAttribute("user"));

            //将id存入ThreadLocal
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request, response);
            return;
        }

        log.info("用户未登录");
        //3.资源不直接放行，用户未登录，访问失败，（前端）跳转访问登录界面   通过输出流的方式
        //手动返回json字符串，给前端ajax（响应拦截器：msg= NOTLOGIN,code=0）
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
        return;




    }

    public boolean check(String[] urls, String requestURI) {

        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }


}
